<template>
  <div class="fixed-table-actionbar">
    <div class="search-bar">
      <el-form :model="formItem" :inline="true" class="form-filter" size="mini">
        <el-form-item v-if="typeSearchShow">
          <treeselect
            v-model="formItem.typeCodes"
            :multiple="false"
            :options="typeOptions"
            placeholder="选择资产分类"
            @input="typeInput"
          />
        </el-form-item>
        <el-form-item v-if="orgSearchShow && categories !== '3'" v-role="['admin', 'kjAssetAdmin', 'slAssetOwnerAdmin']">
          <treeselect
            v-model="formItem.s_managementOrgCode"
            :multiple="false"
            :options="availableOganizations"
            :disable-branch-nodes="true"
            placeholder="请选择管理部门"
            @input="globalSearch"
          />
        </el-form-item>
        <el-form-item v-if="statusSearchShow && categories !== '3'">
          <el-select v-model="formItem.s_status" filterable clearable placeholder="请选择资产状态" @change="globalSearch">
            <el-option v-for="(item) in assetStatus" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="formItem.s_globalSearch"
            placeholder="请输入查询内容..."
            clearable
            @keyup.enter.native="globalSearch"
            @change="onGlobeSearchInputChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button plain icon="el-icon-search" @click="globalSearch" />
        </el-form-item>
      </el-form>
    </div>
    <div v-if="!forSelection" class="action-bar">
      <el-button v-role="['admin', 'kjAssetAdmin', 'slAssetOwnerAdmin', 'kjDeptAssetAdmin']" type="primary" size="mini" icon="el-icon-plus" @click="add">新建</el-button>
      <el-dropdown v-loading="loading" v-role="['admin', 'kjAssetAdmin', 'slAssetOwnerAdmin', 'kjDeptAssetAdmin']" trigger="click">
        <el-button type="primary" size="mini">
          操作<i class="el-icon-arrow-down el-icon--right" />
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-role="['admin', 'kjAssetAdmin', 'slAssetOwnerAdmin']">
            <el-button type="text" size="mini" icon="el-icon-printer" @click="$parent.print($parent.selections)">
              打印标签
            </el-button>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-button type="text" size="mini" icon="el-icon-edit" @click="$parent.edit($parent.selections)">
              编&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;辑
            </el-button>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-button type="text" size="mini" icon="el-icon-delete" @click="$parent.remove($parent.selections)">
              删&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;除
            </el-button>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-button type="text" size="mini" icon="el-icon-download" @click="exportExcel">
              导&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;出
            </el-button>
          </el-dropdown-item>
          <el-dropdown-item v-role="['admin', 'kjAssetAdmin', 'slAssetOwnerAdmin']">
            <el-button size="mini" type="text" icon="el-icon-upload2" @click="uploadDialogFormVisible=true">
              导&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;入
            </el-button>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <FormDialog title="导入" :show="uploadDialogFormVisible" width="40%" @on-ok="closeDialog" @on-cancel="closeDialog">
      <UploadNavigation v-if="uploadDialogFormVisible" :download-funct="template" file-name="资产导入模板" :upload-error="handleError" :action="importExcelurl" :upload-success="handleSuccess" />
    </FormDialog>
    <FormDialog
      title="新建"
      :show="dialogFormVisible"
      width="80%"
      @on-ok="ok"
      @on-cancel="cancel"
    >
      <EditForm ref="editForm" :categories="categories" :belongs="belongs" />
    </FormDialog>
  </div>
</template>

<script>
import { ASSET_STATUS } from '@neu/dcam-ui/utils/constants'
import treeselect from '@neu/biz-core/components/TreeSelect'
import { clone } from '@neu/biz-core/utils/utils'
import { exportExcel, xhExportExcel, importExcelUrl, xhImportExcelUrl, template, xhTemplate } from '@neu/dcam-ui/api/fixedAsset'
import { getToken } from '@neu/biz-core/utils/auth'
import FormDialog from '@neu/biz-core/components/FormDialog'
import { tree as orgTree } from '@neu/auth-ui/api/organization'
import UploadNavigation from '@neu/biz-core/components/UploadNavigation'
import { tree as assetTypeTree } from '@neu/dcam-ui/api/assetType'
import { isEmpty } from '@neu/biz-core/utils'
import { isObject } from '@neu/biz-core/utils/utils'
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import EditForm from './editForm'
/** 全局检索key */
const formItem = {
  s_belongs: '',
  s_locked: null,
  s_categories: '',
  s_globalSearch: '',
  // 管理部门查询
  s_managementOrgCode: null,
  // 小类型
  s_smallTypeCode: null,
  // 大类型
  s_bigTypeCode: null,
  // 中类型
  s_middleTypeCode: null,
  // 资产状态
  s_status: null
}
export default {
  name: 'FixedAssetActionBar',
  components: {
    FormDialog,
    EditForm,
    treeselect,
    UploadNavigation
  },
  props: {
    forSelection: {
      required: false,
      type: Boolean,
      default: false
    },
    lockCodes: {
      type: String,
      default: ''
    },
    status: {
      type: String,
      default: ''
    },
    statusCode: {
      type: String,
      default: ''
    },
    orgIds: {
      type: String,
      default: ''
    },
    belongs: {
      type: String,
      default: null,
      required: true
    },
    categories: {
      type: String,
      default: null,
      required: true
    },
    locked: {
      type: Boolean,
      default: null
    },
    smallTypeCode: {
      type: String,
      default: ''
    },
    typeSearchShow: {
      type: Boolean,
      default: true
    },
    specifications: {
      type: String,
      default: ''
    },
    orgSearchShow: {
      type: Boolean,
      default: true
    },
    statusSearchShow: {
      type: Boolean,
      default: true
    },
    managementOrgCode: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      /** 资产状态 */
      assetStatus: [...ASSET_STATUS],
      /** 加载 */
      loading: false,
      /** 使用部门 */
      availableOganizations: [],
      /** 扁平化类型 */
      flattenTypeTreeData: [],
      /** 检索条件类型 */
      typeCodes: null,
      uploadDialogFormVisible: false,
      /** 资产分类 */
      typeOptions: [],
      /** 绑定的类型编码 */
      assetTypeCode: null,
      formItem: clone(formItem),
      dialogFormVisible: false,
      importExcelurl: this.categories === '3' ? xhImportExcelUrl(this.belongs, this.categories) : importExcelUrl(this.belongs, this.categories),
      template: this.categories === '3' ? xhTemplate(this.belongs) : template(this.belongs),
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Authentication': getToken()
      }
    }
  },
  created() {
    orgTree(this.belongs).then(response => {
      this.availableOganizations = [response.data]
    })
    assetTypeTree(this.belongs, this.categories).then(res => {
      this.typeOptions = res.data
      this.flattenTypeTreeData = this.flattenTreeDataClosure(res.data)
    })
  },
  methods: {
    // 新建用户按钮点击处理
    add() {
      this.dialogFormVisible = true
    },
    // 创建用户对话框确认事件处理
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用pageable-table实例的mixin方法refresh()，更新表格
        this.$parent.refresh()
        this.$refs.editForm.reset()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.$refs.editForm.reset()
      this.dialogFormVisible = false
    },
    exportExcel() {
      this.loading = true
      const searchObj = this.$store.state.dcam.assetSearchObj || {}
      // 清理无效查询项
      let complexSearch = false
      if (Object.keys(searchObj).some(k => isObject(searchObj[k]))) {
        complexSearch = true
      }
      // 清理无效查询项
      for (const k in searchObj) {
        if (complexSearch) {
          if (isEmpty(searchObj[k].value)) delete searchObj[k]
        } else {
          if (isEmpty(searchObj[k])) delete searchObj[k]
        }
      }
      const api = this.categories === '3' ? xhExportExcel : exportExcel
      api(this.belongs, this.categories)(searchObj).then(res => {
        this.loading = false
        const content = res.data
        const blob = new Blob([content])
        const fileName = '导出信息.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleBeforeUpLoad(file) {
      if (file.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        this.$message({
          showClose: true,
          message: '文件 ' + file.name + ' 格式不正确，请上传.xls,.xlsx文件。',
          type: 'error'
        })
      }
    },
    handleError(data) {
      this.$message({
        showClose: true,
        message: data,
        type: 'error'
      })
    },
    globalSearch() {
      if (this.lockCodes) {
        this.formItem['s_lockCodes'] = this.lockCodes
      }
      if (this.status) {
        this.formItem['s_status'] = this.status
      }
      if (this.statusCode) {
        this.formItem['s_statusCode'] = this.statusCode
      }
      if (this.orgIds) {
        this.formItem['s_orgIds'] = this.orgIds
      }
      if (this.smallTypeCode) {
        this.formItem['s_smallTypeCode'] = this.smallTypeCode
      }
      if (this.specifications) {
        this.formItem['s_specifications'] = this.specifications
      }
      if (this.managementOrgCode) {
        this.formItem['s_managementOrgCode'] = this.managementOrgCode
      }
      if (this.locked) {
        this.formItem['s_locked'] = this.locked
      }
      this.$store.dispatch('dcam/setAssetSearchObj', this.formItem)
      // 清除另一个检索form表单
      if (this.$parent.$refs.filterForm) {
        this.$parent.$refs.filterForm.reset()
      }
      // 添加分类
      this.formItem.s_belongs = this.belongs
      this.formItem.s_categories = this.categories
      this.$parent.filter(this.formItem)
      if (!this.formItem['s_managementOrgCode']) {
        this.formItem['s_managementOrgCode'] = null
      }
    },
    reset() {
      this.formItem = clone(formItem)
      this.globalSearch()
    },
    onGlobeSearchInputChange(value) {
      if (value === '') {
        this.globalSearch()
      }
    },
    clearForm() {
      this.formItem = clone(formItem)
    },
    handleSuccess(response) {
      this.uploadDialogFormVisible = false
      this.$message({
        showClose: true,
        message: '资产导入为异步处理，请注意系统通知',
        type: 'success'
      })
      // this.$parent.refresh()
    },
    closeDialog() {
      this.uploadDialogFormVisible = false
      this.$parent.refresh()
    },
    typeInput(value) {
      if (value) {
        const trees = this.findParent(value, this.flattenTypeTreeData)

        if (trees[0] && this.categories !== '3') {
          this.formItem.s_bigTypeCode = trees[0].code
          this.formItem.s_smallTypeCode = ''
          this.formItem.s_middleTypeCode = ''
        } else if (trees[0] && this.categories === '3') {
          this.formItem.s_bigTypeCode = ''
          this.formItem.s_smallTypeCode = trees[0].code
          this.formItem.s_middleTypeCode = ''
        }

        if (trees[1]) {
          this.formItem.s_middleTypeCode = trees[1].code
          this.formItem.s_smallTypeCode = ''
        }

        if (trees[2]) {
          this.formItem.s_smallTypeCode = trees[2].code
        }
      } else {
        this.formItem.s_smallTypeCode = ''
        this.formItem.s_bigTypeCode = ''
        this.formItem.s_middleTypeCode = ''
      }
      this.globalSearch()
    },
    // 扁平化树形结构
    flattenTreeDataClosure(data) {
      const treeData = data
      const flattenData = []
      function flattenTree(data, parentKey) {
        data.forEach(ele => {
          const { title, code, children } = ele
          flattenData.push({ title, code, parentKey })
          if (children) {
            flattenTree(children, code)
          }
        })
      }
      flattenTree(treeData, null)
      return flattenData
    },
    findParent(item, flattenTree) {
      const parentArr = [] // 存储所有的父级元素
      function find(item, flattenTree) {
        flattenTree.forEach(ele => {
          if (ele.code === item) {
            parentArr.unshift({ code: ele.code, name: ele.title })
            find(ele.parentKey, flattenTree)
          }
        })
      }
      find(item, flattenTree)
      return parentArr
    }
  }
}
</script>
